/**
 * 管理员相关请求模块
 */

import request from '@/utils/request'
import { IListParams, Admin, AdminPostData } from './types/admin'
import { IFormData } from './types/form'

export const getAdmins = (params: IListParams) => { // 管理员列表
  return request<{
    count: string
    list: Admin[]
  }>({
    method: 'GET',
    url: '/setting/admin',
    params
  })
}

export const createAdmin = (data: AdminPostData) => { // 添加管理员
  return request({
    method: 'GET',
    url: '/setting/admin',
    data
  })
}

export const updateAdmin = (id: number, data: AdminPostData) => { // 编辑管理员
  return request({
    method: 'PUT',
    url: `/setting/admin/${id}`,
    data
  })
}

export const deleteAdmin = (id: number) => { // 删除管理员
  return request({
    method: 'DELETE',
    url: `/setting/admin/${id}`
  })
}

export const updateAdminStatus = (id: number, status: number) => { // 更新管理员状态
  return request({
    method: 'PUT',
    url: `/setting/set_status/${id}/${status}`
  })
}

export const getRoles = () => { // 管理员角色
  return request<IFormData>({
    method: 'GET',
    url: 'setting/admin/create'
  }).then(data => {
    const roles = data.rules.find(item => item.field === 'roles')
    if (roles && roles.options) {
      return roles.options
    }
    return []
  })
}

export const getAdmin = (id: number) => { // 管理员信息
  return request<IFormData>({
    method: 'GET',
    url: `setting/admin/${id}/edit`
  }).then(data => {
    const obj: Record<string, any> = {}
    data.rules.forEach(item => {
      obj[item.field] = item.value
    })
    return obj as AdminPostData
  })
}
